﻿using DTOs;
using JWT.Builder;
using OA.IBLL;
using OA.Models;
using OA.WebAPI.App_Start;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.ApplicationServices;
using System.Web.Caching;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Web.Http.Results;
using System.Web.Security;

namespace OA.WebAPI.Filtes
{
    public class OAAuthAttribute : AuthorizationFilterAttribute
    {
        JsonMediaTypeFormatter formatter = new JsonMediaTypeFormatter();
        public ISysRoleService RoleService { get; set; }
        public override async Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
        {
            // 如果方法被标注为 AllowAnonymous ，则放行
            if (actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any())
            {
                return; // 已完成的Task

            }
            if (actionContext.Request.Headers.Authorization != null) // 如果用户已登录
            {
                //当前访问的是那个控制器的方法
                var controller = actionContext.ActionDescriptor.ControllerDescriptor.ControllerName;

                var action = actionContext.ActionDescriptor.ActionName;
                var method = actionContext.Request.Method.ToString();// 请求方式

                //用户是什么角色，有那些权限
                var token = actionContext.Request.Headers.Authorization.ToString();
                UserInfoDto userData=null;
                try
                {
                    userData = JWTHelper.DecodeToken(token);
                }
                catch(Exception ex)
                {
                    actionContext.Response = new HttpResponseMessage()
                    {
                        StatusCode=System.Net.HttpStatusCode.Unauthorized,
                        // Content = new StringContent(ex.Message)
                        Content = new ObjectContent(typeof(CommonResult), new CommonResult(ex.Message, null), formatter)
                    };
                    return;
                }

                var userRoles = userData.RolesId.Split(',');
                var allActions = new List<SysAction>();

                foreach (string rid in userRoles)
                {
                    int id = int.Parse(rid);
                    var role = await RoleService.GetEntityAsync(x => x.Id == id);
                    allActions = allActions.Union(role.SysActions).ToList(); // 并集
                }

                // 如果拥有权限
                if (allActions.Any(a => a.ActionName.ToUpper() == action.ToUpper() && a.ControllerName.ToUpper() == controller.ToUpper() && a.Method.ToUpper() == method.ToUpper()))
                {
                    return; // 放行
                }
                else
                {
                    
                    
                    actionContext.Response = new HttpResponseMessage()
                    {
                        StatusCode = System.Net.HttpStatusCode.Unauthorized,
                        // Content = new StringContent("没有权限")
                        Content = new ObjectContent(typeof(CommonResult), new CommonResult("没有权限", null,403,false),formatter)
                    };
                    return;
                }


            }
            else // 用户没有登录
            {
                actionContext.Response = new HttpResponseMessage()
                {
                    StatusCode = System.Net.HttpStatusCode.Unauthorized,
                    //Content = new StringContent("没有登录")
                    Content = new ObjectContent<CommonResult>( new CommonResult("没有登录", null,401,false), formatter)
                };
                return;
            }
                
            
        }
        
    }
}